/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ez2find.services;

import com.ez2find.model.RegisterUser;
import java.io.UnsupportedEncodingException;
import javax.ejb.Stateless;
import java.text.DateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author Owner
 */
@Stateless
public class EmailBean implements EmailLocal {

    private static final String mailer = "JavaMailer";
    private static Logger logger = Logger.getLogger("com.ez2find.services.EmailBean");
    @Resource(name = "mail/myMailSession")
    private Session sessionMail;

    public EmailBean() {
    }

    public void sendAccountConfirmation(RegisterUser recipient) throws Exception {
        Message message = new MimeMessage(sessionMail);
        message.setFrom();
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient.getEmail(), false));
        message.setSubject("Account Confirmation from eez2find");

        DateFormat dateFormatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
        Date timeStamp = new Date(System.currentTimeMillis());

        String messageText = "Thank you for your registration to eez2find.com" + '\n' + "Now please click on the link to confirm the email address and to complete your registration:" + '\n' + '\n' + "'http://www.eez2find.com/site-es/faces/confirmation.html?id=" + recipient.getEncryptedId() + "&cc=" + recipient.getConfirmationCode() + "'" + '\n' + '\n' + "With your new account you can administer all posting published in eez2find.com" + '\n' + "Your register on eez2find.com on " + dateFormatter.format(recipient.getRegisterDate()) + ".";

        message.setText(messageText);
        message.setHeader("X-Mailer", mailer);
        message.setSentDate(timeStamp);

        // Send message
        Transport transport = sessionMail.getTransport("smtp");
        transport.connect("webadmin", "web@dmin");
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        logger.info("Account Confirmation Mail sent to " + recipient.getEmail() + ".");
    }

    public void sendRecoveryConfirmation(RegisterUser recipient) throws Exception {
        Message message = new MimeMessage(sessionMail);
        message.setFrom();
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient.getEmail(), false));
        message.setSubject("Recovery Confirmation from eez2find account");

        DateFormat dateFormatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
        Date timeStamp = new Date(System.currentTimeMillis());
        String messageText = "Thank you for your continue to eez2find.com" + '\n' + "Now please click on the link to confirm the email address and to change your password:" + '\n' + '\n' + "'http://www.eez2find.com/site-es/faces/confirmation.html?id=" + recipient.getEncryptedId() + "&cc=" + recipient.getConfirmationCode() + "'" + '\n' + '\n' + "With your account you can administer all posting published in eez2find.com" + '\n' + "Your register on eez2find.com on " + dateFormatter.format(recipient.getRegisterDate()) + ".";

        message.setText(messageText);
        message.setHeader("X-Mailer", mailer);
        message.setSentDate(timeStamp);

        // Send message
        Transport transport = sessionMail.getTransport("smtp");
        transport.connect("webadmin", "web@dmin");
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        logger.info("Recovery Confirmation Mail sent to " + recipient.getEmail() + ".");
    }

    public void addAnonymousEmail(String type, long code, String email) throws Exception {
        Runtime rt = Runtime.getRuntime();
        String[] command = {"sh", "-c", "echo '" + type + "-" + code + "@eez2find.com " + email + "' >> /etc/mail/virtusertable"};
        rt.exec(command);
        String[] command1 = {"sh", "-c", "makemap hash /etc/mail/virtusertable.db < /etc/mail/virtusertable"};
        rt.exec(command1);
    }

    public void deleteAnonymousEmail(String type, long code, String email) throws Exception {
        Runtime rt = Runtime.getRuntime();
        String[] command = {"sh", "-c", "sed -i '/"+ type +"-" + code + "@eez2find.com " + email + "/d' /etc/mail/virtusertable"};
        rt.exec(command);
        String[] command1 = {"sh", "-c", "makemap hash /etc/mail/virtusertable.db < /etc/mail/virtusertable"};
        rt.exec(command1);
    }

    public void sendMessage(String f, String t, String s, String m) {
        System.out.println("Sending email... ");
        try {
            Properties props = sessionMail.getProperties();
            String username = (String) props.get("mail.smtp.user");
            String password = (String) props.get("mail.smtp.password");

            Message message = new MimeMessage(sessionMail);
            message.setFrom();
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(t, false));
            message.setSubject(s);

            DateFormat dateFormatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
            Date timeStamp = new Date(System.currentTimeMillis());
            String messageText = m;

            InternetAddress from = new InternetAddress();
            from.setAddress("gollum@golum.com");
            if (!f.isEmpty()) {
                from.setAddress(f);
            }
            message.setFrom(from);
            message.setText(messageText);
            message.setHeader("eez2find", mailer);
            message.setSentDate(timeStamp);

            // Send message
            //Transport.send(message);
            Transport transport = sessionMail.getTransport("smtp");
            transport.connect(username, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            logger.info("Forum email sent to " + t + ".");
        } catch (MessagingException ex) {
            ex.printStackTrace();
            logger.info("Error in Forum email for " + t);
        }
    }

    public Boolean sendPost(String f, String t, String s, String m) throws UnsupportedEncodingException {
        System.out.println("Sending email... ");
        try {
            Properties props = sessionMail.getProperties();
            String username = (String) props.get("mail.smtp.user");
            String password = (String) props.get("mail.smtp.password");

            Message message = new MimeMessage(sessionMail);
            message.setFrom();
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(t, false));
            message.setSubject(s);

            DateFormat dateFormatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
            Date timeStamp = new Date(System.currentTimeMillis());
            String messageText = m;

            InternetAddress from = new InternetAddress();
            Address addr = new InternetAddress("anonymus@eez2find.com", "anonymus@xxxxanons.com");
            //from.setAddress(addr);
            if (!f.isEmpty()) {
                addr = new InternetAddress(f);
                //from.setAddress(f);
            }
            message.setFrom(addr);
            message.setText(messageText);
            message.setHeader("eez2find", mailer);
            message.setSentDate(timeStamp);

            // Send message
            //Transport.send(message);
            System.out.println("Sender: " + message.getFrom().toString());
            Transport transport = sessionMail.getTransport("smtp");
            transport.connect(username, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            logger.info("Forum email sent to " + t + ".");
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
            logger.info("Error in Forum email for " + t);
            return false;
        }
    }
}
